import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../model/home_headimageModel.dart';
import '../../utils/tools/commonFooter.dart';
import 'logic.dart';

class HomeMainPage extends StatefulWidget {
  const HomeMainPage({Key? key}) : super(key: key);

  @override
  State<HomeMainPage> createState() => _HomeMainPageState();
}

class _HomeMainPageState extends State<HomeMainPage> {
  final logic = Get.put(HomeMainLogic());

  @override
  void initState() {
    super.initState();
    logic.loadData(); // ✅ 只执行一次
  }
  String formatTime(int? timestamp) {
    if (timestamp == null || timestamp == 0) return '';

    final date = DateTime.fromMillisecondsSinceEpoch(timestamp);
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
  Widget buildImageItem(RxList<homeHeadImageModel> imageUrl) {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child:
      CarouselSlider(
          items: imageUrl.map((e) => Image.network(e.coverImage ?? ""))
              .toList(),
          // items: imageUrl.map((e) => Image.network(e)),
          options: CarouselOptions(
            autoPlay: true, // 自动播放
            enlargeCenterPage: true, // 中间放大效果
            aspectRatio: 16 / 9, // 宽高比
            viewportFraction: 1, // 可见区域占比
          )),
    );
  }

  Widget _buildTextItem(String item) {
    return Column(
      children: [
        Container(height: 40, color: Colors.white,),
        Container(
            width: double.infinity,
            color: Colors.white,
            child: Container(
              height: 22,
              margin: EdgeInsets.only(left: 12),
              child: Text(item,
                style: TextStyle(color: Color(0xFF333333),
                    fontSize: 16,
                    fontWeight: FontWeight.w600),
              ),
            )

        ),
        Container(
          color: Colors.white,
          child: Container(
            height: 1,
            margin: EdgeInsets.only(left: 12, bottom: 0, right: 0, top: 15),
            color: Color(0xFFE4E4E5),
          ),

        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          Container(
            height: 77,
            color: Colors.white,
            alignment: Alignment.bottomCenter,
            child: const Text(
              '精准防艾',
              style: TextStyle(color: Colors.black, fontSize: 20),
            ),
          ),
          Expanded(
              child: Obx(() {
                return Container(
                  child: SmartRefresher(
                    controller: logic.homeRefreshController,
                    enablePullDown: true,
                    enablePullUp: true,
                    header: commonHeader(),
                    // ✅ 使用通用 Header
                    footer: commonFooter(),
                    onRefresh: logic.onRefresh,
                    onLoading: logic.onLoading,
                    child: ListView.builder(
                        padding: EdgeInsets.only(top: 0),
                        itemCount: 2 + logic.invoiceList.length,
                        itemBuilder: (context, index) {
                          if (index == 0) {
                            return Obx(() {
                              return buildImageItem(logic.imageModels);
                            });
                          }
                          if (index == 1) {
                            return _buildTextItem('新闻资讯');
                          }
                          final item = logic.invoiceList[index - 2];
                          return NewsListItem(imageUrl: item.coverImage,title: item.title ?? "", viewCount: "${item.pvCnt}", publishDate: formatTime(item.publishTime));
                        }
                    ),
                  ),
                );
              })
          )
        ],
      ),

    );
  }
}

class NewsListItem extends StatelessWidget {
  final String? imageUrl;
  final String title;
  final String viewCount;
  final String publishDate;

  const NewsListItem({
    super.key,
    this.imageUrl,
    required this.title,
    required this.viewCount,
    required this.publishDate,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
      child: Column(
        children: [
          IntrinsicHeight(//强制 Row 的所有子组件（左侧图片、右侧内容）高度一致，以最大子组件高度为准
            child:   Row(
              children: [
                // 左侧图片
                Container(
                  width: 114,
                  height: 75,
                  margin: EdgeInsets.only(top: 12,bottom: 12),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                    image: imageUrl != null && imageUrl!.isNotEmpty
                        ? DecorationImage(
                      image: NetworkImage(imageUrl!),
                      fit: BoxFit.cover,
                    )
                        : DecorationImage(
                      image: AssetImage('assets/images/default_thumb.png'),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                // child: imageUrl != null && imageUrl!.isNotEmpty
                //     ? Image.network(imageUrl!, fit: BoxFit.cover)
                //     : Image.asset('assets/images/default_thumb.png', fit: BoxFit.cover),
                const SizedBox(width: 12),
                // 右侧内容
                Expanded(
                    child:
                    Container(
                      margin:  EdgeInsets.only(top:14),
                      child:  Column(
                        mainAxisSize: MainAxisSize.max,
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        // mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Container(
                            width: double.infinity,
                            margin: EdgeInsets.only(left: 12,right: 12),
                            child: Text(
                              title,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Color(0xFF333333),
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                          ),
                          // const SizedBox(height: 10),
                          const Spacer(),
                          Container(
                            margin: EdgeInsets.only(bottom: 12),
                            child: Row(
                              children: [
                                const SizedBox(width: 12),
                                Text(
                                  '浏览$viewCount',
                                  style: const TextStyle(fontSize: 12, color: Color(0xFF666666)),
                                ),
                                const Spacer(),
                                Text(
                                  publishDate,
                                  style: const TextStyle(fontSize: 12, color: Color(0xFF666666)),
                                ),
                                const SizedBox(width: 12),
                              ],
                            ),
                          )
                        ],
                      ),
                    )
                ),
                const SizedBox(width: 15),
              ],
            ),
          ),

          Container(
            height: 0.5,
            color: Color(0xFFE4E4E5),
          )
        ],
      ),
    );
  }
}